import { login, logout, getInfo, phoneLogin } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

const user = {
  state: {
    // 0是未执行新手指导 1为已指导
    guide:1,
    // 用于存储首页的课程id和班级id
    currentCourse: '',
    // 用于存储消息页面的课程id和班级id
    messageSearchStorage: {
      classId: '',
      courseId: '',
      sortType: '0',
      msgStatus: 0
    },
    token: getToken(),
    name: '',
    account:'',
    avatar: '',
    phoneNumber: '',
    roles: [],
    roleList: [],
    permissions: [],
    teacherId: '',
    studentId: '',
    schoolId: '',
    branchId: '',
    roleId: '',
    turnRoleId: '',
    schoolInfo: {},
    keepTab: [],
    notice: [],
    checkType: '',
    userId: '',
    msgShow: true,
    groupType: 1,
    studentCardSort: 2,
    cacheSemester: null,
    Switchvalue:1,
    teachGroupType:1,
    teachStudentSort:1,
    GroupListSort:1,
    EN:['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
    topicTypeText: {
      0: "单选题",
      1: "多选题",
      2: "判断题",
      3: "填空题",
      4: "简答题",
      5: "操作题",
      6: "虚拟仿真题",
    },
    difficultyText: {
      0: "简单",
      1: "中等",
      2: "困难",
      3: "不限难度"
    },
    // 教学树状展开状态
    isClose:false,
    // 教学树状选中节点
    activeNode:{},
    customModalVisible: false

  },

  mutations: {
    SET_guide: (state, guide) => {
      state.guide = guide
    },
    SET_currentCourse: (state, currentCourse) => {
      state.currentCourse = currentCourse
    },
    SAVE_CHECKTYPE: (state, checkType) => {
      state.checkType = checkType
    },
    SET_studentId: (state, studentId) => {
      state.studentId = studentId
    },
    SET_keepTab: (state, keepTab) => {
      state.keepTab = keepTab
    },
    SET_teacherId: (state, teacherId) => {
      state.teacherId = teacherId
    },
    SET_branchId: (state, branchId) => {
      state.branchId = branchId
    },
    SET_schoolId: (state, schoolId) => {
      state.schoolId = schoolId
    },

    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_ACCOUNT: (state, account) => {
      state.account = account
    },
    SET_ROLEID: (state, roleKey) => {
      state.roleId = roleKey
    },
    SET_TURNROLEID: (state, roleId) => {
      state.turnRoleId = roleId
    },
    SET_SCHOOL: (state, schoolInfo) => {
      state.schoolInfo = schoolInfo
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_USERID: (state, userId) => {
      state.userId = userId
    },
    SET_phoneNumber: (state, phoneNumber) => {
      state.phoneNumber = phoneNumber
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_ROLELISTS: (state, roleList) => {
      state.roleList = roleList
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_NOTICE: (state, notice) => {
      state.notice = notice
    },
    SET_GROUPTYPE: (state, groupType) => {
      state.groupType = groupType
    },
    SET_STUDENTCARDSORT: (state, sort) => {
      state.studentCardSort = sort
    },
    SET_SCHOOL_SEMESTER: (state, cacheSemester) => {
      state.cacheSemester = cacheSemester;
    },
    SET_SWITCHVALUE: (state, value) => {
      state.Switchvalue = value
    },
    SET_TEACHGROUPTYPE: (state, type) => {
      state.teachGroupType = type
    },
    SET_TEACHSTUDENTSORT: (state, sort) => {
      state.teachStudentSort = sort
    },
    SET_GROUPLISTSORT: (state, sort) => {
      state.GroupListSort = sort
    },
    SET_CLOSE: (state, isClose) => {
      state.isClose = isClose
    },
    SET_ACTIVENODE: (state, activeNode) => {
      state.activeNode = activeNode
    },
    SET_CUSTOMMODALVISIBLE: (state, visible) => {
      state.customModalVisible = visible
    }
  },

  actions: {

    SET_TOKEN({ commit }, token) {
      commit('SET_TOKEN', token)
    },
    saveCheckType({ commit }, checkType) {
      commit('SAVE_CHECKTYPE', checkType)
    },
    Setguide({ commit }, guide) {
      commit('SET_guide', guide)
    },
    SetCurrentCourse({ commit }, obj) {
      commit('SET_currentCourse', obj)
    },
    SetKeepTab({ commit }, obj) {
      commit('SET_keepTab', obj)
    },
    SetGroupType({ commit }, type) {
      commit('SET_GROUPTYPE', type)
    },
    SetStudentCardSort({ commit }, sort) {
      commit('SET_STUDENTCARDSORT', sort)
    },
    SetSchoolSemester({ commit }, semester) {
      commit("SET_SCHOOL_SEMESTER", semester);
    },
    SetSwitchValue({ commit }, value) {
      commit('SET_SWITCHVALUE', value)
    },
    SetTeachGroupType({ commit }, type) {
      commit('SET_TEACHGROUPTYPE', type)
    },
    SetTeachStudentSort({ commit }, sort) {
      commit('SET_TEACHSTUDENTSORT', sort)
    },
    SetGroupListSort({ commit }, sort) {
      commit('SET_GROUPLISTSORT', sort)
    },
    SetClose({ commit }, isClose) {
      commit('SET_CLOSE', isClose)
    },
    SetActiveNode({ commit }, activeNode) {
      commit('SET_ACTIVENODE', activeNode)
    },
    changeCustomModalVisible({ commit }, visible) {
      commit('SET_CUSTOMMODALVISIBLE', visible)
    },
    // 登录
    Login({ commit }, userInfo) {
      let username
      if (userInfo.username.trim() == 'admin') {
        username = userInfo.username.trim()
      } else {
        username = userInfo.sign + userInfo.username.trim()
      }
      const password = btoa(`hgcc${userInfo.password}`);
      const code = userInfo.code;
      const uuid = userInfo.uuid;
      const port = 2;
      const platform = 'pc';
      let params={
        username,
        password,
        code,
        uuid,
        port,
        platform
      }
      return new Promise((resolve, reject) => {
        login(params)
          .then((res) => {
            resolve(res)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 手机号验证登录
    phoneLogin({ commit }, params) {
      return new Promise((resolve, reject) => {
        phoneLogin(params)
          .then((res) => {
            setToken(res.token)
            commit('SET_TOKEN', res.token)
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // admin用户直登  存储token
    setV2Token({ commit }, token) {
      return new Promise((resolve) => {
        setToken(token)
        commit('SET_TOKEN', token)
        resolve()
      })
    },

    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            const user = res.user

            let  avatar =''
            if(user.avatar == '' || user.avatar == null){
              let colorList = [
                "#4e8dff",
                "#28b28b",
                "#f89a33",
                "#fe5394",
                "#e179ed",
                "#40c2a1",
                "#ff7c32",
              ];
              const randomIndex = Math.floor(Math.random() * colorList.length);

              avatar = colorList[randomIndex];
            }else{
              avatar= user.avatar
            }


            if (res.roles && res.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              commit('SET_ROLES', res.roles)
              commit('SET_ROLELISTS', res.roleList)
              commit('SET_PERMISSIONS', res.permissions)
            } else {
              commit('SET_ROLES', ['ROLE_DEFAULT'])
            }
            commit('SET_guide', user.guide)
            commit('SET_NAME', user.nickName)
            commit('SET_ACCOUNT', user.account)
            commit('SET_ROLEID', res.currentUserRole.roleKey)
            commit('SET_TURNROLEID', res.currentUserRole.roleId)
            commit('SET_SCHOOL', res.school)
            commit('SET_AVATAR', avatar)
            commit('SET_USERID', user.userId)
            commit('SET_phoneNumber', user.phoneNumber)
            commit('SET_teacherId', user.typeId)
            commit('SET_studentId', user.typeId)
            commit('SET_branchId', res.currentUserRole.branchId ? res.currentUserRole.branchId : user.branchId)
            commit('SET_schoolId', user.schoolId)
            commit('SET_NOTICE', res.notice)
            resolve(res)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            commit('SET_PERMISSIONS', [])
            commit('SetKeepTab', [])
            removeToken()
            localStorage.clear()
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
